package com.zhiwei.msf.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhiwei.msf.common.constant.CommonErrorConstants;
import com.zhiwei.msf.common.constant.ResultResponseMsg;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author ZHIWEI.YANG
 * @createtime 2019/2/1 - 17:02
 * @decription 异常捕获全局类
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Autowired
    private MessageSource messageSource;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultResponseMsg errorMsg(HttpServletRequest request, Exception ex) {
        log.error("===> HTTP请求访问路径异常URL: {}", request.getRequestURL(), ex);
        if (ex instanceof BasePublishException) {
            BasePublishException exception = (BasePublishException) ex;
            String exceptionMsg = exception.getMessage();
            if (StringUtils.isEmpty(exceptionMsg)) {
                exceptionMsg = messageSource.getMessage(exception.getCode(), exception.getArgs(), Locale.getDefault());
            }
            return ResultResponseMsg.buildResultMsg(((BasePublishException) ex).getCode(), exceptionMsg, null);
        } else {
            String exceptionMessage = messageSource.getMessage(CommonErrorConstants.UNKNOWN, null, Locale.getDefault());
            return ResultResponseMsg.buildResultMsg(CommonErrorConstants.UNKNOWN, exceptionMessage, null);
        }
    }
}